package cn.wenzy.aurora.admin.oauth2.configuration;

import cn.wenzy.aurora.admin.oauth2.encoder.SM3PasswordEncoder;
import cn.wenzy.aurora.admin.oauth2.userdetails.SysUserCache;
import cn.wenzy.aurora.admin.oauth2.userdetails.SysUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class Oauth2SecurityConfig {

    @Autowired
    private SysUserDetailsService userDetailsService;
    @Autowired
    private SysUserCache userCache;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new SM3PasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false); // 设置用户不存在时，抛出 usernotfoundexception
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        provider.setUserCache(userCache);
        return provider;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // TODO spring security 登陆
        http.userDetailsService(userDetailsService);
        return http.build();
    }

}
